package com.hkbigdata.transform;

import com.hkbigdata.entry.WaterSensor;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.Arrays;
import java.util.List;

/**
 * @author liuanbo
 * @creat 2023-03-19-12:35
 * @see 2194550857@qq.com
 */
public class Flink11_TransFrom_Reduce {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        List<WaterSensor> waterSensors = Arrays.asList(
                new WaterSensor("ws_001", 1607527992000L, 20),
                new WaterSensor("ws_001", 1607527992001L, 22),
                new WaterSensor("ws_001", 1607527992002L, 33),
                new WaterSensor("ws_002", 1607527992003L, 44),
                new WaterSensor("ws_002", 1607527992004L, 22),
                new WaterSensor("ws_002", 1607527992001L, 50)
        );

        KeyedStream<WaterSensor, String> waterSensorStringKeyedStream = env.fromCollection(waterSensors)
                .keyBy(WaterSensor::getId);

/*        SingleOutputStreamOperator<WaterSensor> reduce = waterSensorStringKeyedStream.reduce(new RichReduceFunction<WaterSensor>() {
            @Override
            public WaterSensor reduce(WaterSensor value1, WaterSensor value2) throws Exception {
                return new WaterSensor(value1.getId(), value1.getTs(), value1.getVs() + value2.getVs());
            }
        });*/

        SingleOutputStreamOperator<WaterSensor> reduce = waterSensorStringKeyedStream.reduce((value1, value2) -> {
            return new WaterSensor(value1.getId(), value1.getTs(), value1.getVs() + value2.getVs());
        });

        reduce.print();

        env.execute();
    }
}
